import axios from 'axios';
import { useUserStore } from '@/stores';
import { ElMessage } from 'element-plus';


 const baseURL =import.meta.env.VITE_BASE_URL
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000
});
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const token = userStore.token;
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; 
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => response.data.data,
  (error) => {
    const { response } = error;
    let errorMsg = '请求失败，请稍后重试';

    if (response) {
      const { code, message } = response.data;
      errorMsg = message || errorMsg;

      switch (code) {
        case 401:
          ElMessage({
            message: errorMsg,
            type: 'error',
            duration: 3000
          });
        console.log('401', errorMsg);
          window.location.href = '/login';
          break;

        case 400:
          ElMessage.error(errorMsg);
          break;

        case 404:
          ElMessage.error(errorMsg);
          break;
          
        case 500:
          ElMessage({
            message: `服务器错误：${errorMsg}`,
            type: 'error',
            duration: 5000
          });
          break;

        default:
          ElMessage.error(errorMsg);
      }
    } else {
      ElMessage({
        message: '网络连接失败，请检查网络',
        type: 'error',
        duration: 3000
      });
    }

    return Promise.reject(error);
  }
);

export default instance;    